<template>
  <div>
    <van-notify id="van-notify" />
    <van-row>
      <van-col span="24" v-for="(lendClass, index) in AlllendClass" :key="index">
        <van-sticky>
          <div v-show="(index === 0)?true:false" ><van-divider contentPosition="center" customStyle="color: #1989fa;border-color: #1989fa;font-size: 18px;" :value="lendClass.date">{{lendClass.date}}</van-divider></div>
        </van-sticky>
        <van-collapse :value="activeNames" @change="onChange"  >
          <van-collapse-item class="title" :title="openid === lendClass._openid?`${lendClass.classroom}(我的申请)      ${lendClass.startTime}-${lendClass.endTime}`:`${lendClass.classroom}      ${lendClass.startTime}-${lendClass.endTime}`" :name="index">
            <p>班级/部门: {{lendClass.department}}</p><br>
            <p>用途: {{lendClass.use}}</p><br>
            <p>联系方式: {{lendClass.phonenumber}}</p>
            <button @click="update(lendClass._id)" type="primary" size="mini" v-show="(openid === lendClass._openid)?true:false">修改</button>
            <button @click="dalete(lendClass._id)" type="warn" size="mini" v-show="(openid === lendClass._openid)?true:false">删除</button>
            <button @click="dalete(lendClass._id)" type="warn" size="mini" v-show="(openid === 'o8T3n5fMWItxP0DpdTJLncMxc5Qg')?true:false">管理员删除</button>
          </van-collapse-item>
        </van-collapse>
      </van-col>
    </van-row>
    <i-button size="small" type="primary" @click="addLendClass" shape="circle">申请教室</i-button>
  </div>
</template>

<script>
  import DateFormat from "../../../utils/dateFormat";
  import Notify from 'static/vant/notify/notify';
  export default {
    data() {
      return {
        userInfo: {},
        avatarUrl: '',
        nickName: '',
        openid: '',
        AlllendClass: [],
        activeNames: ['1'],
        isShow: false,
        dateTime : DateFormat(new Date(new Date().setDate(new Date().getDate()+2)).toDateString())
      }
    },
    onShow() {
      this.handleGetUserInfo();
      this.restart()
    },
    onLoad() {
      this.handleGetUserInfo();
      this.restart()
    },
    methods: {
      // 验证是否登陆过
      restart() {
        const db = wx.cloud.database({env: 'xxzx1201-gxxma'});
        // 获取当天教室占用情况
        db.collection('lendClass').where({ date: this.dateTime }).orderBy('classroom', 'asc').get({
          success: (res) =>  this.AlllendClass = res.data
        })
      },
      handleGetUserInfo() {
        wx.getUserInfo({
          success: (res) => {
            this.avatarUrl = res.userInfo.avatarUrl;
            this.nickName = res.userInfo.nickName;
            wx.cloud.callFunction({
              name: 'login',
              complete: res => {
                this.openid = res.result.openid
                this.userInfo = {
                  avatarUrl: this.avatarUrl,
                  nickName: this.nickName,
                  openid: this.openid
                };
                this.$store.commit("saveUserInfo", this.userInfo);
              }
            });
          },
          fail: (res) => {
            this.isShow = false
            wx.navigateTo({
              url: '/pages/login/index'
            })
          }
        });
      },
      onPullDownRefresh() {
        setTimeout(() => {
          Notify({ type: 'success', message: '刷新成功', duration:1500})
        },1100)
        wx.stopPullDownRefresh()
        this.restart()
      },
      onChange(event) {
        this.activeNames = event.detail
      },
      onChange1(event) {
        this.activeNames = event.detail
      },
      onChange2(event) {
        this.activeNames = event.detail
      },
      addLendClass() {
        const db = wx.cloud.database({env: 'xxzx1201-gxxma'});
        db.collection('lendClass').where({ _openid: this.openid, date: this.dateTime }).count({
          success: (res) => {
            if (res.total >= 1) {
              setTimeout(() => {
                Notify({ type: 'danger', message: '无申请次数', duration:1000});
              })
              return
            }
            wx.navigateTo({
              url: '/pages/add/index'
            })
          }
        })
      },
      dalete(id) {
        const db = wx.cloud.database({env: 'xxzx1201-gxxma'});
        if (this.adminOpenid === 'o8T3n5fMWItxP0DpdTJLncMxc5Qg') {
          wx.cloud.callFunction({
            // 云函数名称
            name: 'adminDelete',
            data: {
              id: id
            },
            success: (res) => {
              Notify({ type: 'success', message: '删除成功', duration:1000});
              this.restart()
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1
                })
              }, 1000)
            },
            fail: console.error
          })
          return
        }
        db.collection('lendClass').doc(id).remove({
          success: (res) => {
            wx.showToast({
              title: '删除成功',
              icon: 'success'
            })
            this.restart()
            this.restart()
            setTimeout(() => {
              this.restart()
            }, 1500)
          }
        })
      },
      update(e) {
        this.$store.commit('saveId', e)
        wx.navigateTo({
          url: '/pages/update/index',
        })
      },
      findTomorrow() {
        wx.navigateTo({
          url: '/pages/tomorrow/index',
        })
      },
      findAcquired() {
        wx.navigateTo({
          url: '/pages/index/acquired/index',
        })
      }
    }
  }
</script>

<style>

</style>
